package pw.hais.utils;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;

import java.lang.reflect.Field;

/**
 * ViewHolder 工具类
 * Created by Administrator on 2015/4/8.
 */
public class ViewHolderUtils {
    private static final String ID = "id";

    /**
     * 加载视图，并反射控件
     * @param mContext 上下文
     * @param convertView   view
     * @param layoutId  布局
     * @param cls   Holder类
     * @return
     */
    public static View loadingConvertView(Context mContext, View convertView, int layoutId, Class<?> cls) {
        try {
            if (convertView == null) {
                convertView = LayoutInflater.from(mContext).inflate(layoutId, null);
                Object obj = cls.newInstance();
                Field[] mFields = obj.getClass().getDeclaredFields();

                for (Field mField : mFields) {
                    int resourceId = mContext.getResources().getIdentifier(mField.getName(), ID, mContext.getApplicationContext().getPackageName());
                    mField.setAccessible(true);
                    mField.set(obj, convertView.findViewById(resourceId));
                }
                convertView.setTag(obj);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return convertView;
    }
}
